package uit.comm.util;

import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class MRUCache {

	private int cacheSize;
	private Map cache;
	private List keyList;

	public MRUCache(){
		this.cacheSize = 100;
		this.cache = Collections.synchronizedMap(new HashMap());
		this.keyList = Collections.synchronizedList(new LinkedList());
	}


	/**
	 * Add an object to the cache
	 *
	 * @param key        The key of the object to be cached
	 * @param value      The object to be cached
	 */
	public void putObject(Object key, Object value) {
		cache.put(key, value);
		keyList.add(key);
		if (keyList.size() > cacheSize) {
			try {
				Object oldestKey = keyList.remove(0);
				cache.remove(oldestKey);
			} catch (IndexOutOfBoundsException e) {
				//ignore
			}
		}
	}

	/**
	 * Get an object out of the cache.
	 *
	 * @param key        The key of the object to be returned
	 * @return The cached object (or null)
	 */
	public Object getObject( Object key) {
		return cache.get(key);
	}

	public Object removeObject(Object key) {
		keyList.remove(key);
		return cache.remove(key);
	}

	/**
	 * Flushes the cache.
	 *
	 */
	public void flush() {
		cache.clear();
		keyList.clear();
	}

}
